package com.lz.sports.dialog

import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.lz.comm.net.HttpManager
import com.lz.library.dialog.BaseDialogFragment
import com.lz.sports.LogUtils
import com.lz.sports.R
import com.lz.sports.api.DownloadApi
import com.lz.sports.databinding.DialogZipDownloadBinding
import com.lz.sports.utils.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream


//ZIP压缩包
class ZipDownloadDialog : BaseDialogFragment<DialogZipDownloadBinding>() {

    companion object {

        fun show(activity: FragmentActivity, url: String, tmpPath: String, path: String): ZipDownloadDialog {
            val dialog = ZipDownloadDialog().also {
                it.arguments = Bundle().apply {
                    putString("url", url)
                    putString("tmpPath", tmpPath)
                    putString("path", path)
                }
            }
            dialog.setFrom(true)
            dialog.show(activity.supportFragmentManager)
            return dialog
        }
    }

    override fun getLayoutRes(): Int = R.layout.dialog_zip_download

    override fun initData(v: View, savedState: Bundle?) {
        val url = arguments!!.getString("url")!!
        val tmpPath = arguments!!.getString("tmpPath")!!
        val path = arguments!!.getString("path")!!

        val downloadApi = HttpManager.getService(DownloadApi::class.java)
        if (downloadApi == null) {
            dismiss()
            return
        }
        lifecycleScope.launch {
            val job = async(Dispatchers.IO) {
                val response = downloadApi.download(url).execute()
                if (response.code() == 200) {
                    val body = response.body()
                    if (body == null) {
                        false
                    } else {
                        download(File(tmpPath), File(path), body, binding)
                    }
                } else {
                    false
                }
            }
            if (job.await()) {
                downloadListener?.onResult(this@ZipDownloadDialog, path)
            } else {
                ToastUtils.showMyToast(R.string.downloadingErr)
            }
            dismiss()
        }
    }

    private var lastModifyTime = 0L
    private fun download(tmpFile: File, zip: File, responseBody: ResponseBody, pb: DialogZipDownloadBinding): Boolean {
        try {
            val length = responseBody.contentLength()
            val inputStream = responseBody.byteStream()
            FileOutputStream(tmpFile).use { fos ->
                val buf = ByteArray(1024 * 4)
                var len: Int
                var count: Long = 0
                while (inputStream.read(buf).also { len = it } > 0) {
                    fos.write(buf, 0, len)
                    count += len.toLong()
                    val currentTime = System.currentTimeMillis()
                    if (currentTime - lastModifyTime >= 300) {
                        lastModifyTime = currentTime
                        pb.progress = (count * 100 / length).toInt()
                    }
                }
            }
            tmpFile.renameTo(zip)
            return true
        } catch (e: Exception) {
            LogUtils.i("err = $e")
            tmpFile.delete()
        }
        return false
    }

    var downloadListener: DownloadListener? = null

    interface DownloadListener {

        fun onResult(dialog: ZipDownloadDialog, path: String)
    }
}